import { createSlice } from "@reduxjs/toolkit";
import {req} from "@/utils";
import { getToken,setToken as _setToken } from "../../utils";
const userStore = createSlice({
    name:"user",
    initialState:{
      token:getToken() || ''
    },
    reducers:{
      setToken(state,action){
        state.token = action.payload
        _setToken(action.payload)
      }
    }
})

const { setToken } = userStore.actions;
const userReducer = userStore.reducer;


const fetchLogin = (loginForm)=>{
  return async(dispatch)=>{
    const res = await req.post('/login',loginForm)
    console.log(res);
    dispatch(setToken(res))
    return res;
  }
}

const fetchsendVerification = (loginForm)=>{
  return async(dispatch)=>{
    const res = await req.post('/registerVerification',loginForm)
   return res;
    
  }
}
// 在 userStore.js 的导出部分添加这两个 action
const createInviteCode = (code) => {
  return async (dispatch) => {
    const res = await req.post('/user/createInviteCode', { code });
    return res;
  }
};

const exchangePoints = (points) => {
  return async (dispatch) => {
    const userId = localStorage.getItem('userId'); // 从 localStorage 获取 userId
    const res = await req.post('/api/seeds/points/exchange', { userId, points });
    return res;
  }
};
// 在 userStore.js 中添加
const fetchInviteCodes = () => {
  return async (dispatch) => {
    const res = await req.get('/user/getInviteCode');
    return res;
  }
};
const fetchregister = (loginForm)=>{
  return async(dispatch)=>{
    const res = await req.post('/register',loginForm)
    console.log(res);
    return res;
  }
}
const fetchUserList = (params = {}) => {
  return async (dispatch) => {
    try {
      const { page = 1, size = 10, keyword = '' } = params;
      const res = await req.get('/user/getUserList', {
        params: { page, size, keyword }
      });
      return res;
    } catch (error) {
      console.error('获取用户列表失败:', error);
      throw error;
    }
  };
};
const modifyUserPoints = (data) => {
  return async (dispatch) => {
    try {
      const res = await req.post('/api/seeds/points/receive', data);
      return res;
    } catch (error) {
      console.error('修改用户积分失败:', error);
      throw error;
    }
  };
};

const banUser = (userId) => {
  return async (dispatch) => {
    try {
      const res = await req.post(`/user/ban/${userId}`);
      return res;
    } catch (error) {
      console.error('封禁用户失败:', error);
      throw error;
    }
  };
};

const unbanUser = (userId) => {
  return async (dispatch) => {
    try {
      const res = await req.post(`/user/unban/${userId}`);
      return res;
    } catch (error) {
      console.error('解封用户失败:', error);
      throw error;
    }
  };
};

const fetchUserInfo = ()=>{
  return async(dispatch)=>{
    const res = await req.get('/user/profile')
    
    return res;
  }
}
const fetchUserProfile = (id)=>{
  return async(dispatch)=>{
    const res = await req.get(`/user/${id}/profile`)
    
    return res;
  }
}
const modifyUserInfo = (values)=>{
  return async(dispatch)=>{
    const res = await req.put('/user/profile',values)
    return res;
  }
}

const fetchresetVerification = ()=>{
  return async(dispatch)=>{
    const res = await req.post('/user/resetVerification')
    return res;
  }
}
const modifypassword = (values)=>{
  return async(dispatch)=>{
    const res = await req.post('/user/password',values)
    return res;
  }
}

const uploadAvatar = (fromdata)=>{
  return async(dispatch)=>{
    const res = await req.post('/user/uploadAvatar',fromdata)
    return res;
  }
}

const downloadTorrent = (data)=>{
  return async(dispatch)=>{
    const res = await req.post('/tracker/downloadTorrent',data)
   return res;
    
  }
}

// 关注用户
 const followUser = (userId) => async () => {
  const res = await req.post(`/user/follow/${userId}`);
  return res;
};

// 取消关注用户
 const deFollowUser = (userId) => async () => {
  const res = await req.post(`/user/deFollow/${userId}`);
  return res;
};
const fetchUserTorrents = (params = {}) => async (dispatch) => {
  try {
    const { userId, page = 1, size = 3 } = params; // 默认每页3条
    
    const response = await req.get(`/tracker/getUserTorrentList/${userId}`, {
      params: { 
        page, 
        size 
      }
    });
    
    
      return response;
    
   
  } catch (err) {
   
    throw err;
  }
};
// 在userStore中添加
const togglePromotionRuleStatus = (data) => async () => {
  try {
    const response = await req.post('/api/promotion-rules/deactivate', data);
    return response;
  } catch (err) {
    console.error('修改规则状态失败:', err);
    throw err;
  }
};
// 在userStore中添加
const createPromotionRule = (ruleData) => async () => {
  try {
    const response = await req.post('/api/promotion-rules', ruleData);
    return response;
  } catch (err) {
    console.error('创建促销规则失败:', err);
    throw err;
  }
};

const fetchTorrentList = (params = {}) => async (dispatch) => {
  try {
    const { id, page = 1, size = 10, categoryId } = params;
    
    let response;
    if (id) {
      // 单个种子查询
      response = await req.post('/tracker/getTorrentList', { id });
    } else {
      // 分页查询（新增categoryId参数）
      response = await req.post('/tracker/getTorrentList', {}, {
        params: { 
          page, 
          size,
          categoryId: categoryId || undefined // 不传categoryId时发送undefined
        }
      });
    }
    
    if (response.code === 0) {
      return response;
    }
    throw new Error(response.msg || '获取种子列表失败');
  } catch (err) {
    console.error('获取种子列表错误:', err);
    throw err;
  }
};
 const deleteInviteCode = (code) => {
  return async (dispatch) => {
    try {
      const res = await req.post('/user/deleteInviteCode', { code });
      return res;
    } catch (error) {
      console.error('删除邀请码出错:', error);
      throw error;
    }
  };
};

const uploadTorrent = (formdata)=>{
  return async(dispatch)=>{
    const res = await req.post('/tracker/uploadTorrent',formdata)
    return res;
  }
}
// 在userStore.js中添加
 const addInviteCodeUses = (code) => {
  return async (dispatch) => {
    try {
      const res = await req.post('/user/addInviteCodeUses', { code });
      return res;
    } catch (error) {
      console.error('增加邀请码次数出错:', error);
      throw error;
    }
  };
};
const createTorrent = (formdata)=>{
  return async(dispatch)=>{
    const res = await req.post('/tracker/createTorrent',formdata)
    return res;
  }
}

const getFollowsList = () => async () => {
  try {
    const response = await req.get('/user/follows');
    return response;
  } catch (err) {
    console.error('获取关注列表错误:', err);
    throw err;
  }
};
const fetchComments = (params = {})=>{
  return async(dispatch)=>{
    const res = await req.get('/api/seeds/getCommentList',{ params })
    return res;
  }
}


const addComment = (data)=>{
  return async(dispatch)=>{
    console.log("addComment:", data);
    const res = await req.post('/api/seeds/comment',data)
    return res;
  }
}
const likeComment = (data)=>{
  return async(dispatch)=>{
    console.log("likeComment:", data);
    const res = await req.post('/api/seeds/likes',data);
    console.log("likeComment return:", res);
    return res;
  }
}

const deleteComment = (data)=>{
  return async(dispatch)=>{
    console.log("deleteComment:", data);
    const res = await req.post('/api/seeds/deleteComment',data)
    return res;
  }
}
 const getPromotionRules  = () => {
  return async (dispatch) => {
    try {
      const res = await req.get('/api/promotion-rules');
      console.log(res)
      return res;
    } catch (err) {
      console.error('获取促销规则失败:', err);
      throw err;
    }
  };
};
const getFansList = () => async () => {
  try {
    const response = await req.get('/user/fans');
    return response;
  } catch (err) {
    console.error('获取粉丝列表错误:', err);
    throw err;
  }
};


export{ setToken ,fetchregister,fetchsendVerification,fetchLogin,fetchUserInfo,modifyUserInfo,
  modifypassword,fetchresetVerification,uploadAvatar,fetchTorrentList,fetchUserProfile,followUser,
  deFollowUser,uploadTorrent,downloadTorrent,createTorrent,getFollowsList,getFansList,fetchUserTorrents,
 getPromotionRules ,createPromotionRule,togglePromotionRuleStatus,createInviteCode,exchangePoints,fetchInviteCodes,
unbanUser,banUser,fetchUserList,modifyUserPoints,deleteComment,likeComment,addComment,fetchComments,addInviteCodeUses,deleteInviteCode}
export default userReducer